#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date    : 2014-08-18 15:31:46
# @Author  : shitao.tommy (hero007asd@gmail.com)
# @Link    : http://example.org
# @Version : $Id$

from tornado.web import RequestHandler
from framework.minirest import auth
from lib import log
from lib.libjson import to_json,to_utf8_json
from lib import libtime
import traceback
# import tornado_mysql

ip_list = ('127.0.0.1','114.94.246.201','114.91.44.0', '116.226.47.95','114.88.149.152')

class BaseApiHandler(RequestHandler):
    def initialize(self):
        pass
        # self.start_time = libtime.get_now_timestamp()
        #初始化db连接
        # self.conn = yield tornado_mysql.connect(host='114.215.130.186', port=3306, user='root', passwd='1234567890', db='weixin')
        # pass

    def prepare(self):
        request_ip = self.request.remote_ip
        if not request_ip in ip_list:
            self.write_fail(None, 410, '非法ip地址访问')
            self.finish()
        #validate key
        # key = self.get_argument('key', default='')
        # keyOk, keyMsg = auth.validate_key(key)
        # if keyOk == False:
        #     self.write(keyMsg)
        #     self.finish()
        # else:
        #     #validate ip
        #     ipOk, ipMsg = auth.validate_ip(self.request.remote_ip)
        #     if ipOk == False:
        #         self.write(ipMsg)
        #         self.finish()
        #     else:
        #         #validate signature
        #         args = self.request.query.split('&')
        #         signature = self.get_argument('signature', default='')
        #         timestamp = self.get_argument('timestamp', default='')
        #         for arg in args:
        #             if arg.startswith('signature'):
        #                 args.pop(args.index(arg))
        #         params = '&'.join(args)
        #         signatureOk, signatureMsg = auth.validate_signature(key, params, timestamp, signature)
        #         if signatureOk == False:
        #             self.write(signatureMsg)
        #             self.finish()

    def on_finish(self):
        # cost_time = libtime.get_now_timestamp() - self.start_time
        cost_time = int(self.request.request_time() * 1000)
        # if len(str(self.result)) > 500:
        #     resp_ret = str(len(str(self.result)))
        # else: resp_ret = to_utf8_json(self.result)

        if hasattr(self,'result'):
            if len(str(self.result)) > 500:
                resp_ret = str(len(str(self.result)))
            else:
                resp_ret = to_utf8_json(self.result)
        else: resp_ret = '0'
        # print self.request.headers['User-Agent']
        log.log_api(self.get_status(), self.request.method, self.request.uri, self.request.remote_ip,
         '%sms' % cost_time,self.request.arguments, 'size:%s' % resp_ret)

        e = traceback.format_exc()
        if e.strip() != 'None':
            log.log_exception(self.__class__.__name__, e)

    def write_success(self, data, msg=''):
        self.result = {'status':200, 'message':msg, 'data':to_json(data)}
        self.write(self.result)

    def write_fail(self, data=None, code=500, msg=''):
        self.result = {'status':code, 'message':msg, 'data':to_json(data)}
        self.write(self.result)

    def write_info(self, data=[], msg=''):
        if data == '0':
            self.write_fail(None, 400,  '未查到相关数据')
        elif data == '-1':
            self.write_fail(None, 500, '系统错误')
        elif data == '-2':
            self.write_fail(None, 401, '数据已存在')
        else:
            self.write_success(data, msg)

